package com.yanze.schoolinformation.view.community.circle;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;

import com.example.xrecyclerview.XRecyclerView;
import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.adapter.rv.DynamicAdapter;
import com.yanze.schoolinformation.app.AppConfig;
import com.yanze.schoolinformation.databinding.ActivityFriendBinding;
import com.yanze.schoolinformation.model.bean.resp.RespDynamic;
import com.yanze.schoolinformation.model.bean.resp.RespUser;
import com.yanze.schoolinformation.utils.PerfectClickListener;
import com.yanze.schoolinformation.utils.ToastUtils;
import com.yanze.schoolinformation.viewModule.circle.FriendCircleNavigator;
import com.yanze.schoolinformation.viewModule.circle.FriendCircleViewModel;

public class FriendCircleActivity extends AppCompatActivity implements FriendCircleNavigator {

    private ActivityFriendBinding bindingView;
    private View refresh;//错误布局
    private FriendCircleViewModel viewModel;
    private DynamicAdapter mAdapter;
    private Animation rotateAnimation;
    private LocalBroadcastManager localBroadcastManager;
    private PublishReceive mPublishReceive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindingView = DataBindingUtil.setContentView(this, R.layout.activity_friend);
        // 解决7.0以上系统 滑动到顶部 标题裁减一半的问题
        setSupportActionBar(bindingView.toolbar);
        bindingView.toolbarLayout.setTitle("校友圈");

        viewModel = new FriendCircleViewModel(this);
        viewModel.setmNavigator(this);
        initAnimator();
        initRecyclerView();
        viewModel.getDynamics();

        //注册本地广播
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        mPublishReceive = new PublishReceive();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.schoolinformation.publishdynamic");
        localBroadcastManager.registerReceiver(mPublishReceive, intentFilter);
    }

    private void initAnimator() {
        //默认进入界面就开启动画
        rotateAnimation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//        rotateAnimation.setFillAfter(true); // 设置保持动画最后的状态
        rotateAnimation.setDuration(1000); // 设置动画时间
        rotateAnimation.setInterpolator(new AccelerateDecelerateInterpolator()); // 设置插入器
        rotateAnimation.setRepeatCount(Animation.INFINITE);
        bindingView.fabRefresh.setAnimation(rotateAnimation);
        bindingView.fabRefresh.setClickable(false);
        rotateAnimation.start();
    }

    private void initRecyclerView() {
        refresh = getView(R.id.ll_error_refresh);
        refresh.setOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                onRefresh();
            }
        });

        bindingView.xrvDynamics.setPullRefreshEnabled(false);
        bindingView.xrvDynamics.setLoadingMoreEnabled(true);
        bindingView.xrvDynamics.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new DynamicAdapter(this);
        bindingView.xrvDynamics.setAdapter(mAdapter);
        bindingView.xrvDynamics.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                viewModel.setmPage(viewModel.getmPage() + 1);
                viewModel.getDynamics();
            }
        });
    }

    /**
     * 悬浮按钮点击
     *
     * @param view
     */
    public void addDynamic(View view) {
        RespUser.UserInfo user = AppConfig.getUserInfo(this);
        if (user != null) {
            PublishDynamicActivity.start(this, 1);
        }else{
            ToastUtils.show(this,"登陆后才能发表动态~");
        }
    }

    /**
     * 刷新按钮
     */
    public void refDynamic(View view) {
        mRefreshStart(true);
    }

    /**
     * 触发刷新/关闭刷新
     */
    private void mRefreshStart(boolean isLoding) {
        if (isLoding) {
            bindingView.fabRefresh.setClickable(false);
            bindingView.fabRefresh.setAnimation(rotateAnimation);
            bindingView.fabRefresh.startAnimation(rotateAnimation);
//            rotateAnimation.start();
            bindingView.fabRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    viewModel.setmPage(1);
                    viewModel.getDynamics();
                }
            }, 1000);
        } else {
            bindingView.fabRefresh.setClickable(true);
            rotateAnimation.cancel();
            bindingView.fabRefresh.clearAnimation();
        }
    }

    private void showContentView() {
        if (refresh.getVisibility() != View.GONE) {
            refresh.setVisibility(View.GONE);
        }
        if (bindingView.xrvDynamics.getVisibility() != View.VISIBLE) {
            bindingView.xrvDynamics.setVisibility(View.VISIBLE);
        }
    }

    private void showError() {
        refresh.setClickable(true);
        if (refresh.getVisibility() != View.VISIBLE) {
            refresh.setVisibility(View.VISIBLE);
        }
        if (bindingView.xrvDynamics.getVisibility() != View.GONE) {
            bindingView.xrvDynamics.setVisibility(View.GONE);
        }
    }

    protected <T extends View> T getView(int id) {
        return (T) findViewById(id);
    }

    @Override
    public void showLoadSuccessView() {
        showContentView();
    }

    @Override
    public void onRefreshSuccess(RespDynamic entity) {
        mRefreshStart(false);

        mAdapter.clear();
        mAdapter.addAll(entity.getData());
        mAdapter.notifyDataSetChanged();
        bindingView.xrvDynamics.refreshComplete();
    }

    @Override
    public void onLoadMoreSuccess(RespDynamic entity) {
        mAdapter.addAll(entity.getData());
        mAdapter.notifyDataSetChanged();
        bindingView.xrvDynamics.refreshComplete();
    }

    @Override
    public void showNoMoreLoading() {
        bindingView.xrvDynamics.noMoreLoading();
    }

    @Override
    public void showLoadFailedView() {
        mRefreshStart(false);
        bindingView.fabRefresh.setClickable(false);

        bindingView.xrvDynamics.refreshComplete();
        if (mAdapter.getItemCount() == 0) {
            showError();
        }
    }

    private void onRefresh() {
        mRefreshStart(true);
        refresh.setClickable(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(mPublishReceive);
        viewModel.onDestory();
    }

    /**
     * 广播接收器
     */
    class PublishReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mRefreshStart(true);
        }
    }

    /**
     * 入口
     */
    public static void start(Context context) {
        Intent intent = new Intent(context, FriendCircleActivity.class);
        context.startActivity(intent);
    }
}
